from time import time
from copy import copy, deepcopy
from bbpeer import BBPeer
from random import shuffle

class BitBrook(object):
    TIMEOUT = 86400 # Wait for a day before expiring.
    REQPEERS = 4 # How many peers should be returned in response to a request.

    def __init__(self, bid, peer):
        super(BitBrook, self).__init__()
        
        self.bid = bid
        self.peers = [peer]
        self.last_activity = time()

    def update_timestamp(self):
        self.last_activity = time()

    def add_peer(self, peer):
        # If the peer is already there we just silently ignore this.
        if not peer in self.peers:
            self.peers.append(peer)
            
    def remove_inactive_peers(self, now):
        for peer in copy(self.peers):
            if now - peer.timestamp > BBPeer.ACTIVITY_TIMEOUT:
                # Remove this inactive peer.
                self.peers.remove(peer)

    def get_random_peers(self):
        randpeers = []
        if len(self.peers) <= BitBrook.REQPEERS:
            # Return all peers since we have less that REQPEERS.
            for peer in self.peers:
                randpeers.append(peer.addr)
        else:
            # Select REQPEERS random peers.
            peers = deepcopy(self.peers)
            shuffle(peers)
            for peer in peers[:BitBrook.REQPEERS]:
                randpeers.append(peer.addr)
        return randpeers
            
    def update_peer_activity(self, peer):
        # Find the peer object and update its timestamp.
        peer = self.peers[self.peers.index(peer)]
        peer.update_timestamp()

    def remove_peer(self, peer):
        # Find and remove the peer object.
        self.peers.pop(self.peers.index(peer))
        
